import React, { Component } from 'react';
import { Drawer, Button, Form, TimePicker, Upload, Tooltip, InputNumber, message, Modal, Table } from 'antd';
import './index.scss';
import { FormInstance } from 'antd/lib/form';
import { RcCustomRequestOptions } from 'antd/lib/upload/interface';
import moment from 'moment';
import parseInfoMain from './parseAttendanceFileToModel';
import { attendanceRecordModel, AttendanceRecordModel, resetStore } from './parseAttendanceFileToModel/store';
import Column from 'antd/lib/table/Column';

const { Dragger } = Upload;

const { RangePicker } = TimePicker;

export interface Props {
    onImportData?: (model: AttendanceRecordModel) => void;
    onError?: (err?: any) => void;
    onReset?: () => void;
}

export default class ImportData extends Component<Props> {
    state = {
        drawerVisible: true,
        isModalVisible: false,
        modalContent: ''
    }

    closeDrawer = () => {
        this.setState({
            drawerVisible: false
        });
    }

    openDrawer = () => {
        this.setState({
            drawerVisible: true
        });
    }

    formRef = React.createRef<FormInstance>();
    reset = () => {
        if (this.formRef.current !== null) {
            this.formRef.current.resetFields();
        }
        resetStore();
        if (typeof this.props.onReset === 'function') {
            this.props.onReset();
        }
    }

    getDraggerFile = (e: any) => {
        if (Array.isArray(e.fileList)) {
            return e.fileList;
        }
        return [];
    }

    messageKey = 'updatable';
    submit = (e: any) => {
        if (typeof e === 'object') {
            resetStore();
            if (typeof this.props.onReset === 'function') {
                this.props.onReset();
            }
            message.loading({ key: this.messageKey, content: '正在解析数据', duration: 0 });
            const {
                departmentInfoFileList,
                workerInfoFileList,
                attendanceDataFileList,
                clockMoment,
                lateAndEarlyMoment,
                officialHolidays,
            } = e;
            parseInfoMain({
                departmentInfoFileList,
                workerInfoFileList,
                attendanceDataFileList,
                clockMoment,
                lateAndEarlyMoment,
                officialHolidays
            }).then(() => {
                const { undefinedWorkerList } = attendanceRecordModel;
                if (typeof this.props.onImportData === 'function') {
                    this.props.onImportData(attendanceRecordModel);
                }
                this.closeDrawer();
                message.success({ key: this.messageKey, content: '数据解析成功' });
                if (undefinedWorkerList.length > 0) {
                    this.showModal(
                        <>
                            <h3>程序在统计《考勤信息》时未匹配到以下员工信息，未匹配到员工信息的数据不会进行考勤统计，如果不重要，请忽略，如果重要，请检查《员工信息》表中以下员工信息是否正确。</h3>
                            <Table
                                dataSource={undefinedWorkerList}
                                size="small"
                            >
                                <Column title="工作簿" dataIndex="workBook" />
                                <Column title="表" dataIndex="sheet" />
                                <Column title="工号" dataIndex="id" />
                                <Column title="姓名" dataIndex="name" />
                                <Column title="部门" dataIndex="department" />
                            </Table>
                        </>
                    );
                }
            }, err => {
                message.destroy(this.messageKey);
                if (typeof this.props.onError === 'function') {
                    this.props.onError(err);
                }
                this.showModal(err);
            });
        }
    }

    loadFile = (options: RcCustomRequestOptions) => {
        if (options.file.type === 'application/vnd.ms-excel' || options.file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
            options.onSuccess({ errCode: 0, errMsg: 'ok' }, options.file);
        } else {
            this.showModal('仅支持 xls 或 xlsx 格式文件。');
            options.onError(new Error('仅支持 xls 或 xlsx 格式文件'));
        }
    }

    onFinishFailed = () => {
        this.showModal('如果您想让程序帮你处理数据，您需要导入必要的数据。');
    }

    showModal = (content: React.ReactNode) => {
        this.setState({
            isModalVisible: true,
            modalContent: content
        });
    }

    hideModal = () => {
        this.setState({
            isModalVisible: false,
            modalContent: ''
        });
    }

    render() {
        return (
            <div className="import-file">

                <Tooltip placement="right" title="导入数据">
                    <i
                        className="iconfont drawer-open-btn"
                        onClick={this.openDrawer}
                    >
                        &#xe601;
                    </i>
                </Tooltip>

                <Modal
                    visible={this.state.isModalVisible}
                    closable={false}
                    maskClosable={false}
                    cancelButtonProps={{
                        hidden: true
                    }}
                    title="温馨提示"
                    okText="知道了"
                    onOk={this.hideModal}
                >
                    {this.state.modalContent}
                </Modal>

                <Drawer
                    className="drawer"
                    title="导入考勤文件，并填写配置信息"
                    placement="left"
                    width="400px"
                    closable={false}
                    onClose={this.closeDrawer}
                    visible={this.state.drawerVisible}
                >
                    <Form
                        className="params-form"
                        layout="vertical"
                        requiredMark="optional"
                        onFinish={this.submit}
                        onFinishFailed={this.onFinishFailed}
                        ref={this.formRef}
                    >

                        <Form.Item
                            name="departmentInfoFileList"
                            label="部门信息表 (可上传多个)"
                            valuePropName="fileList"
                            getValueFromEvent={this.getDraggerFile}
                        >
                            <Dragger
                                className="form-item-inner"
                                multiple
                                customRequest={this.loadFile}
                                accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                            >
                                点击或拖拽上传文件
                            </Dragger>
                        </Form.Item>

                        <Form.Item
                            name="workerInfoFileList"
                            label="员工信息表 (可上传多个)"
                            valuePropName="fileList"
                            required
                            getValueFromEvent={this.getDraggerFile}
                            rules={[{ required: true, message: '请至少上传一个员工信息 Excel 表格文件' }]}
                        >
                            <Dragger
                                className="form-item-inner"
                                multiple
                                customRequest={this.loadFile}
                                accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                            >
                                点击或拖拽上传文件
                            </Dragger>
                        </Form.Item>

                        <Form.Item
                            name="attendanceDataFileList"
                            label="考勤记录表 (可上传多个)"
                            required
                            valuePropName="fileList"
                            getValueFromEvent={this.getDraggerFile}
                            rules={[{ required: true, message: '请至少上传一个考勤记录 Excel 表格文件' }]}
                        >
                            <Dragger
                                className="form-item-inner"
                                multiple
                                customRequest={this.loadFile}
                                accept="application/vnd.ms-excel,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                            >
                                点击或拖拽上传文件
                            </Dragger>
                        </Form.Item>

                        <Form.Item
                            name="clockMoment"
                            label="默认上下班打卡时间"
                            required
                            rules={[{ required: true, message: '请填写默认上下班打卡时间' }]}
                            initialValue={[moment('08:30:00', 'HH:mm:ss'), moment('18:00:00', 'HH:mm:ss')]}
                            tooltip="统计时会优先使用部门信息表中的数据，当未查询到员工所属部门时会使用该数据"
                        >
                            <RangePicker
                                className="form-item-inner"
                                placeholder={['上班打卡时间', '下班打卡时间']}
                            />
                        </Form.Item>

                        <Form.Item
                            name="lateAndEarlyMoment"
                            label="默认迟到和早退计算缺勤时间"
                            required
                            rules={[{ required: true, message: '请填写迟到缺勤和早退缺勤时间' }]}
                            initialValue={[moment('09:00:00', 'HH:mm:ss'), moment('17:00:00', 'HH:mm:ss')]}
                            tooltip="统计时会优先使用部门信息表中的数据，当未查询到员工所属部门时会使用该数据"
                        >
                            <RangePicker
                                className="form-item-inner"
                                placeholder={['最晚上班打卡时间', '最早下班打卡时间']}
                            />
                        </Form.Item>

                        <Form.Item
                            name="officialHolidays"
                            label="本次统计周期公休节假日天数 (天)"
                            required
                            initialValue={4}
                        >
                            <InputNumber
                                className="form-item-inner"
                                placeholder="公休日天数"
                                min={0}
                                max={31}
                            />
                        </Form.Item>

                        <Form.Item className="submit-from-item">
                            <Button className="button" type="primary" onClick={this.reset}>清空</Button>
                            <Button className="button" type="primary" htmlType="submit">开始处理</Button>
                        </Form.Item>
                    </Form>
                </Drawer>
            </div >
        );
    }
}
